﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Principal;
using System.Windows;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;

namespace LprMiddleWare
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        public App()
        {
            Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
        }

        void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.ToString());
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = (Exception)e.ExceptionObject;

            _logger.FatalException("程序发生未知异常, 程序将会被关闭", ex);

            MessageBox.Show("程序发生未知异常，请重新启动程序。");
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            if (Process.GetProcessesByName(Assembly.GetExecutingAssembly().GetName().Name).Length > 1)
            {
                MessageBox.Show("程序已经在运行，本程序实例即将退出。", "中间件");
                System.Windows.Application.Current.Shutdown();
                return;
            }

            var settings = Settings.LoadDefault();
            settings.Validate();

            if (settings.HasErrors)
            {
                MessageBox.Show("系统配置有错误或者是第一次启动系统，请重新配置系统选项");
            }

            _logger.Info("程序启动成功");

        }

    }
}
